package com.bestcem.xm.common.core.sign.grpc.interceptor;

import com.bestcem.xm.common.core.sign.grpc.core.GrpcTemplate;
import io.grpc.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/7/14 14:52
 */

@Slf4j
public class GrpcClientInterceptor implements ClientInterceptor {

    //@Value("${sms.app-key:35QyFknBZ3pgmp4KB2Ye98KD}")
    //private String appKey;
    //@Value("${sms.app-secret:eFdKo4q8TNkH0xMCe9gFakZSlFAWK7}")
    //private String appSecret;

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method,
                                                               CallOptions callOptions, Channel next) {
        String methodName = method.getFullMethodName();
        // 对短信服务做特殊处理
        // 短信服务已经全部替换成starter
        //if(methodName.startsWith("zhongyan.bp.sms.v1.SmsService")) {
        //    return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
        //        @Override
        //        public void start(Listener<RespT> responseListener, Metadata headers) {
        //            /* put custom header */
        //            headers.put(Metadata.Key.of("app-key", Metadata.ASCII_STRING_MARSHALLER), appKey);
        //            headers.put(Metadata.Key.of("app-secret", Metadata.ASCII_STRING_MARSHALLER), appSecret);
        //            super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
        //                @Override
        //                public void onHeaders(Metadata headers) {
        //                    super.onHeaders(headers);
        //                }
        //            }, headers);
        //        }
        //    };
        //}

        // 调用generateAuth 生成签名,如果无签名则正常调用。有签名则把签名加在header里。
        String authorization = GrpcTemplate.generateAuth(methodName);

        if (Objects.isNull(authorization)) {
            return next.newCall(method, callOptions);
        } else {
            return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
                @Override
                public void start(Listener<RespT> responseListener, Metadata headers) {
                    /* put custom header */
                    headers.put(GrpcInterceptor.META_KEY_AUTHORIZATION, authorization);
                    super.start(new ForwardingClientCallListener.SimpleForwardingClientCallListener<RespT>(responseListener) {
                        @Override
                        public void onHeaders(Metadata headers) {
                            super.onHeaders(headers);
                        }
                    }, headers);
                }
            };
        }
    }
}
